package nc.bs.pub.action;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import nc.bs.common.projectFAUtils;
import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.NCLocator;
import nc.bs.ic.pub.env.ICBSContext;
import nc.bs.ic.pub.util.ICBillVOQuery;
import nc.bs.pub.compiler.AbstractCompiler2;
import nc.bs.scmpub.pf.PfParameterUtil;
import nc.itf.ic.m45.self.IPurchaseInMaintain;
import nc.itf.uif.pub.IUifService;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.vo.ic.m45.entity.BillCPVO;
import nc.vo.ic.m45.entity.PurchaseInBodyVO;
import nc.vo.ic.m45.entity.PurchaseInHeadVO;
import nc.vo.ic.m45.entity.PurchaseInVO;
import nc.vo.ic.pub.pf.ICPFParameter;
import nc.vo.ml.NCLangRes4VoTransl;
import nc.vo.pub.BusinessException;
import nc.vo.pub.compiler.PfParameterVO;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
import nc.vo.trade.billsource.LightBillVO;
import nc.vo.trade.billsource.LinkQueryType;


public class N_45_WRITE extends AbstractCompiler2 {
	private Hashtable m_methodReturnHas = new Hashtable();
	private Hashtable m_keyHas = null;
	private final  String message="Y";
	private String billNO = "";
	private String billFinderClassname = "nc.impl.pubapp.linkquery.BillTypeSetBillFinder";
	private static IUifService service = (IUifService)NCLocator.getInstance().lookup(IUifService.class);
	public Object runComClass(PfParameterVO vo) throws BusinessException {
		try {
			super.m_tmpVo = vo;
			ICBSContext context = new ICBSContext();
			context.setICPFParameter((ICPFParameter) this.getUserObj());
			PurchaseInVO[] inVOs = (PurchaseInVO[]) ((PurchaseInVO[]) this.getVos());
			
			//lhw 231207 begin
			new projectFAUtils().projectDataApprove("ic_purchasein_h",inVOs, "save");
			//end
			
			

			
			if (null != inVOs[0] && null != inVOs[0].getHead() && null != inVOs[0].getHead().getCgeneralhid()) {
				PfParameterUtil<PurchaseInVO> util = new PfParameterUtil(this.getPfParameterVO(), inVOs);
				PurchaseInVO[] originBills = (PurchaseInVO[]) util.getOrginBills();
				if (originBills == null) {
					originBills = (PurchaseInVO[]) (new ICBillVOQuery()).fetchVOWithLoc(inVOs);
				}

				PurchaseInVO[] clientFullBills = (PurchaseInVO[]) util.getClientFullInfoBill();
				PurchaseInVO[] inVOsC = (PurchaseInVO[]) ((PurchaseInVO[]) this.getVos());
				 //修改库存
				  setNumberKC(inVOsC,"1");
			     PurchaseInVO[] result=((IPurchaseInMaintain) NCLocator.getInstance().lookup(IPurchaseInMaintain.class))
				.update(clientFullBills, originBills);
			    
			   
				return result;
				
			} else {	
				 PurchaseInVO[] result=((IPurchaseInMaintain) NCLocator.getInstance().lookup(IPurchaseInMaintain.class)).insert(inVOs);
			
				 PurchaseInVO[] inVOsC = (PurchaseInVO[]) ((PurchaseInVO[]) this.getVos());
					PurchaseInHeadVO pcvo= (PurchaseInHeadVO) inVOsC[0].getParentVO();          					        					
				
						List<BillCPVO>   bills=getNobyId(pcvo.getCgeneralhid());
						
						String updateCode=null;
						for(BillCPVO bvo:bills) {
							LightBillVO lvo=bvo.getLightBillVO();
							if(lvo.getType().equals("422X")) {
								updateCode =lvo.getCode();
							}
							
							
						}

						
				if(updateCode!=null) {
					String  updateSql="update po_storereq set vdef1 ='"+message+"' where vbillcode ='"+updateCode+"' ";	
					 //修改库存
					new BaseDAO().executeUpdate(updateSql);
					}
				
			

				 setNumberKC(inVOsC,"0");
				 return result;
			
			}	
			
		} catch (Exception var7) {
			ExceptionUtils.marsh(var7);
			return null;
		}
	}

	public String getCodeRemark() {
		return NCLangRes4VoTransl.getNCLangRes().getStrByID("4008002_0", "04008002-0076");
	}

	private void setParameter(String key, Object val) {
		if (this.m_keyHas == null) {
			this.m_keyHas = new Hashtable();
		}

		if (val != null) {
			this.m_keyHas.put(key, val);
		}

	}
	
	private void  setNumberKC(PurchaseInVO[] inVOsC,String number) throws BusinessException {
		
		Map<String, String> map = new HashMap<>();
		for (PurchaseInVO purchaseInVO : inVOsC) {

			PurchaseInHeadVO pcvo = (PurchaseInHeadVO) purchaseInVO.getParentVO();
			PurchaseInBodyVO[] pcbvos = (PurchaseInBodyVO[]) purchaseInVO.getAllChildrenVO();
			String codeNumber = pcvo.getVbillcode();
			for (PurchaseInBodyVO pcbVo : pcbvos) {
//				
//				String sqlz="	SELECT naccumstorenum FROM po_order_b  pob  LEFT JOIN po_order po "
//						+ " ON po.pk_order =pob.pk_order WHERE po.vbillcode ='"+pcbVo.getVfirstbillcode()+"' AND pob.crowno ='"+pcbVo.getCrowno() +"'";
//				BigDecimal numberZ= (BigDecimal) new BaseDAO().executeQuery(sqlz,new ColumnProcessor());
//			
//				String sqlT="	SELECT nbackstorenum FROM po_order_b  pob  LEFT JOIN po_order po "
//						+ " ON po.pk_order =pob.pk_order WHERE po.vbillcode ='"+pcbVo.getVfirstbillcode()+"'AND pob.crowno ='"+pcbVo.getCrowno() +"'";

				if (number.equals("1")) {
					List<BillCPVO> bills = getNobyId(pcvo.getCgeneralhid());

					String updateCode = null;
					for (BillCPVO bvo : bills) {
						LightBillVO lvo = bvo.getLightBillVO();
						if (lvo.getType().equals("422X")) {
							updateCode = lvo.getCode();
						}

					}

					if (updateCode != null) {
						String sqlNumber = "select nassistnum from  ic_purchasein_b where dr=0 and cgeneralbid='"
								+ pcbVo.getCgeneralbid() + "'";
						BigDecimal noNumber = (BigDecimal) new BaseDAO().executeQuery(sqlNumber, new ColumnProcessor());
						BigDecimal big = BigDecimal.ZERO;
						if (noNumber != null) {
							big = noNumber;
						}
						String sql = "SELECT pob.vsourcerowno FROM po_order  po left join po_order_b pob  on po.pk_order =pob.pk_order WHERE po.vbillcode ='"
								+ pcbVo.getVfirstbillcode() + "' AND pob.crowno='" + pcbVo.getVfirstrowno()
								+ "' and pob.dr=0";

						String no = (String) new BaseDAO().executeQuery(sql, new ColumnProcessor());

						if (no != null) {
							if (!no.equals("~")) {

								List<BillCPVO> billss = getNobyId(pcvo.getCgeneralhid());

								String updateCodez = null;
								for (BillCPVO bvo : billss) {
									LightBillVO lvo = bvo.getLightBillVO();
									if (lvo.getType().equals("422X")) {
										updateCodez = lvo.getCode();
									}
								}
								String sqlnumber = "select pk_storereq_b  from po_storereq_b psb LEFT JOIN  po_storereq ps  ON  ps.pk_storereq = psb.pk_storereq  where  psb.dr=0 and ps.vbillcode='"
										+ updateCodez + "' and psb.crowno='" + no + "'";

								String pkNumber = (String) new BaseDAO().executeQuery(sqlnumber, new ColumnProcessor());
								String sqla = "select vbdef1   from po_storereq_b	where  dr=0 and pk_storereq_b='"
										+ pkNumber + "'";

								Object numberc_obj = new BaseDAO().executeQuery(sqla, new ColumnProcessor());
								BigDecimal newc = BigDecimal.ZERO;
								if (pcbVo.getNassistnum() == null) {
									newc = new BigDecimal(0);
								} else {
									newc = new BigDecimal(pcbVo.getNassistnum().toString());
								}

								BigDecimal cA = big.subtract(newc);
								BigDecimal bigc = BigDecimal.ZERO;
								if (numberc_obj != null && !numberc_obj.equals("~")) {
									bigc = new BigDecimal(numberc_obj.toString());
								}

								BigDecimal bd = bigc.subtract(cA);

								if (bd.compareTo(BigDecimal.ZERO) < 0) {
									throw new BusinessException("数据报错");
								}
								if (updateCodez != null) {
									// 进行校验
									// 判断非空
									// if(null==map.get(pkNumber)) {
									String updateSql = "update po_storereq_b set vbdef1 ='" + bd.toPlainString()
											+ "' where pk_storereq_b ='" + pkNumber + "' ";
									new BaseDAO().executeUpdate(updateSql);
									map.put(pkNumber, "1");
//									}else {
//										String updateSql2="select vbdef1 from po_storereq_b where pk_storereq_b ='"+pkNumber+"'";
//										String numbero=(String) new BaseDAO().executeQuery(updateSql2, new  ColumnProcessor());
//										BigDecimal  bdc= new BigDecimal(bd.toPlainString());
//										BigDecimal  bdo= new BigDecimal(numbero);
//										BigDecimal nbdc=bdc.add(bdo);
//										String  updateSql="update po_storereq_b set vbdef1 ='"+nbdc.toPlainString()+"' where pk_storereq_b ='"+pkNumber+"' ";	
//									    new BaseDAO().executeUpdate(updateSql);
//									}
									// 修改是否入库
									String updateSqlV = "update po_storereq_b set vbdef5 ='" + codeNumber
											+ "' where pk_storereq_b ='" + pkNumber + "' ";
									new BaseDAO().executeUpdate(updateSqlV);
								}

							}
						}
					}

				} else {
					List<BillCPVO> bills = getNobyId(pcvo.getCgeneralhid());

					String updateCode = null;
					for (BillCPVO bvo : bills) {
						LightBillVO lvo = bvo.getLightBillVO();
						if (lvo.getType().equals("422X")) {
							updateCode = lvo.getCode();
						}
					}

					if (updateCode != null) {
						String sqlNumber = "select nassistnum from  ic_purchasein_b where dr=0 and cgeneralbid='"
								+ pcbVo.getCgeneralbid() + "'";
						BigDecimal noNumber = (BigDecimal) new BaseDAO().executeQuery(sqlNumber, new ColumnProcessor());
						BigDecimal big = BigDecimal.ZERO;
						if (noNumber != null) {
							big = noNumber;
						}

						String sql = "SELECT pob.vsourcerowno FROM po_order  po left join po_order_b pob  on po.pk_order =pob.pk_order WHERE po.vbillcode ='"
								+ pcbVo.getVfirstbillcode() + "' AND pob.crowno='" + pcbVo.getVfirstrowno()
								+ "' and pob.dr=0";

						String no = (String) new BaseDAO().executeQuery(sql, new ColumnProcessor());

						if (no != null) {
							if (!no.equals("~")) {

								List<BillCPVO> billss = getNobyId(pcvo.getCgeneralhid());

								String updateCodez = null;
								for (BillCPVO bvo : billss) {
									LightBillVO lvo = bvo.getLightBillVO();
									if (lvo.getType().equals("422X")) {
										updateCodez = lvo.getCode();
									}
								}
								String sqlnumber = "select pk_storereq_b  from po_storereq_b psb LEFT JOIN  po_storereq ps  ON  ps.pk_storereq = psb.pk_storereq  where  psb.dr=0 and ps.vbillcode='"
										+ updateCodez + "' and psb.crowno='" + no + "'";

								String pkNumber = (String) new BaseDAO().executeQuery(sqlnumber, new ColumnProcessor());
								String sqla = "select vbdef1   from po_storereq_b	where  dr=0 and pk_storereq_b='"
										+ pkNumber + "'";

								Object numberc_obj = (Object) new BaseDAO().executeQuery(sqla, new ColumnProcessor());
								BigDecimal bigc = BigDecimal.ZERO;
								if (numberc_obj != null && !numberc_obj.equals("~")) {
									bigc = new BigDecimal(numberc_obj.toString());
								}

								BigDecimal bd = bigc.add(big);

								if (bd.compareTo(BigDecimal.ZERO) < 0) {
									throw new BusinessException("数量存在问题，请检查");
								}
								if (updateCodez != null) {
									// 修改数量
									// 修改入库
									String updateSql = "update po_storereq_b set vbdef1 ='" + bd.toPlainString()
											+ "' where pk_storereq_b ='" + pkNumber + "' ";
									new BaseDAO().executeUpdate(updateSql);
									String updateSqlV = "update po_storereq_b set vbdef5 ='" + codeNumber
											+ "' where pk_storereq_b ='" + pkNumber + "' ";
									new BaseDAO().executeUpdate(updateSqlV);

								}
							}
						}
					}
				}
			}
				
//				String sql= "SELECT psb.pk_storereq_b  FROM po_storereq_b psb LEFT JOIN  po_storereq ps    ON  "
//						+ " ps.pk_storereq= psb.pk_storereq   LEFT JOIN po_praybill_b ppb   ON  "
//						+ " psb.crowno =ppb.vsourcerowno AND ps.vbillcode = ppb.vsourcecode  LEFT JOIN  ct_pu_b cpu ON  "
//						+ "ppb.pk_praybill=CPU.csrcid  AND  cpu.cpraybillrowno= ppb.crowno  LEFT  JOIN  po_order_b pob ON  "
//						+ "CPU.pk_ct_pu =pob.csourceid AND cpu.crowno=pob.crowno  LEFT JOIN  po_order  po  ON   "
//						+ "po.pk_order =pob.pk_order WHERE po.vbillcode ='"+pcbVo.getVfirstbillcode()+"' AND pob.crowno='"+pcbVo.getCrowno()+"'";
	     }
	}
	
	
	
	
	
	public List<BillCPVO> getNobyId(String id){
	LinkQueryType queryType = LinkQueryType.OnlyQueryBill;
	LightBillVO vo = null;

	try {
		vo = service.queryBillGraph(billFinderClassname, id,"45", queryType);
		if (vo != null && StringUtils.isEmpty(vo.getCode())) {
			vo.setCode(billNO);
		}
	} catch (Exception var9) {
		String message = NCLangRes4VoTransl.getNCLangRes().getStrByID("0020nccloud_0", "0ncc0020001-0277");
		Exception ex = new RuntimeException(var9);
		Throwable cause = ExceptionUtils.unmarsh(ex);
		if (var9 != null && cause.getMessage() != null) {
			message = cause.getMessage();
		}

		ExceptionUtils.wrappBusinessException(message);
	}
	
	List<BillCPVO> list = this.dealVO(vo);
	return list;
	}
	
	
	
	
	
	
	
	public List<BillCPVO> dealVO(LightBillVO vo) {
		if (vo == null) {
			return null;
		} else {
			Map<String, BillCPVO> setAll = new LinkedHashMap();
			this.getSource(vo, setAll);
			List<String> sourceList = ((BillCPVO) setAll.get(vo.getID())).getSourceList();
			this.getForward(vo, setAll);
			((BillCPVO) setAll.get(vo.getID())).setIsForward("0");
			((BillCPVO) setAll.get(vo.getID())).setSourceList(sourceList);
			List<BillCPVO> list = new ArrayList(setAll.values());
			return list;
		}
	}

	public void getSource(LightBillVO vo, Map<String, BillCPVO> setAll) {
		if (vo != null) {
			BillCPVO flow = new BillCPVO();
			flow.setLightBillVO(vo);
			flow.setIsForward("-1");
			List<String> sourceList = flow.getSourceList();
			if (vo.getSourceBillVOs() == null) {
				if (setAll.get(vo.getID()) == null) {
					setAll.put(vo.getID(), flow);
				}

			} else {
				LightBillVO[] var5 = vo.getSourceBillVOs();
				int var6 = var5.length;

				for (int var7 = 0; var7 < var6; ++var7) {
					LightBillVO sourVO = var5[var7];
					sourceList.add(sourVO.getID());
					this.getSource(sourVO, setAll);
				}

				vo.setSourceMap(new HashMap());
				flow.setSourceList(sourceList);
				setAll.put(vo.getID(), flow);
			}
		}
	}

	public void getForward(LightBillVO vo, Map<String, BillCPVO> setAll) {
		if (vo != null) {
			BillCPVO flow = new BillCPVO();
			flow.setLightBillVO(vo);
			flow.setIsForward("1");
			List<String> forwardList = flow.getForwardList();
			if (vo.getForwardBillVOs() == null) {
				if (setAll.get(vo.getID()) == null) {
					setAll.put(vo.getID(), flow);
				}

			} else {
				LightBillVO[] var5 = vo.getForwardBillVOs();
				int var6 = var5.length;

				for (int var7 = 0; var7 < var6; ++var7) {
					LightBillVO sourVO = var5[var7];
					forwardList.add(sourVO.getID());
					this.getForward(sourVO, setAll);
				}

				vo.setForwardMap(new HashMap());
				flow.setForwardList(forwardList);
				setAll.put(vo.getID(), flow);
			}
		}
	}
	
	
	
	
}